<?php
include_once ('class.mysql.php');

class RegisterConfigman
{
    private $configman_name;
    private $maintainment_period;
    private $maintainment_period_date;
    private $maintainment_day;
    private $comtec_id_mainteiner;
    private $status_reg;
    
    private $errors;
    private $token;

    public function __construct()
    {
        $this->errors   = array();
	
	$this->configman_name			= $_POST['configman_name'];
	$this->maintainment_period		= $_POST['maintainment_period'];
	$this->maintainment_period_date		= $_POST['maintainment_period_date'];
        if(strlen($this->maintainment_period_date) > 400)
        {
         $this->maintainment_period_date = substr($this->maintainment_period_date,0,400);   
        }
        $this->maintainment_day                 = $_POST['maintainment_day'];
        $this->comtec_id_mainteiner             = $_POST['comtec_id_mainteiner'];
	$this->status_reg			= 1;
        $this->token				= $_POST['token'];
    }

    public function process()
    {
        if($this->valid_token() && $this->valid_data())
            $this->register();

        return count($this->errors)? 0 : 1;
    }

    public function filter($var)
    {
        return preg_replace('/[^a-zA-Z0-9@.]/','',$var);
    }

    public function filter_num($var)
    {
        return preg_replace('/[^0-9+]/','',$var);
    }

    public function register()
    {
        $db = new MySQL();

        $stmt = $db->query("INSERT INTO configman(
	    configman_name,
	    maintainment_period,
	    maintainment_period_date,
            maintainment_day,    
	    status_reg,
            comtec_id_mainteiner    
	) VALUES (
            '$this->configman_name',
	    $this->maintainment_period,
	    '$this->maintainment_period_date',
            $this->maintainment_day,    
            $this->status_reg,
            $this->comtec_id_mainteiner    
        )");

        if($db->affected_rows() < 1)
            $this->errors[] = 'No se puede procesar la inscripci&oacute;n';
    }

    public function user_exists()
    {
        $db = new MySQL();

        $stmt = $db->query("SELECT comtec_id_configman FROM configman WHERE configman_name = '{$this->configman_name}'");

        return $db->num_rows($stmt)? 1 : 0;
    }

    public function show_errors()
    {
        $msg = "";
        foreach($this->errors as $key=>$value)
            $msg = $msg . $value . "\n";
        return $msg;
    }

    public function valid_data()
    {
        if($this->user_exists())
            $this->errors[] = 'Configuracion ya existe';

        return count($this->errors)? 0 : 1;
    }

    public function valid_token()
    {
        if(!isset($_SESSION['token']) || $this->token != $_SESSION['token'])
            $this->errors[] = 'Registro inv&aacute;lido';

        return count($this->errors)? 0 : 1;
    }
}
?>
